package com.atguigu.exam.service.impl;


import com.atguigu.exam.entity.Category;
import com.atguigu.exam.mapper.CategoryMapper;
import com.atguigu.exam.mapper.QuestionMapper;
import com.atguigu.exam.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private QuestionMapper questionMapper;


    @Override
    public List<Category> getCategoriesWithVideoCount(){
        //获取所有分类列表,根据sort排序
        List<Category> categories = baseMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort));
        //获取所有分类下的数量
        List<Map<Long, Long>> countList = questionMapper.getCategoryCount();
        System.out.println(countList);
        //将List<Map<Long, Long>> 转换成Map<Long, Long>
        Map<Long, Long> countMap = countList.stream().collect(Collectors.toMap(
                m -> m.get("category_id"),
                m -> m.get("count")
        ));
        System.out.println(countMap);
        //遍历分类列表，为每个分类设置数量
        categories.forEach(category -> {
         Long questionCount = countMap.getOrDefault(category.getId(), 0L);
         category.setCount(questionCount);
        });
        return categories;
    }

    @Override
    public List<Category> getCategoryTree() {
        //获取所有分类列表,根据sort排序
        List<Category> categories = baseMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort));
        //构建树形结构
        List<Category> categoryTree = buildCategoryTree(categories);
        return categoryTree;
    }
    //构建树形结构的方法
    private List<Category> buildCategoryTree(List<Category> categories) {
        //按照parent_id分组,获取每个父分类下的分类列表
        Map<Long, List<Category>> parentIdMap = categories.stream().collect(Collectors.groupingBy(Category::getParentId));
        //遍历所有分类，为每个分类设置子分类列表
        categories.forEach(category -> {
            List<Category> children = parentIdMap.getOrDefault(category.getId(), new ArrayList<>());
            category.setChildren(children);
        });
        return parentIdMap.getOrDefault(0L, new ArrayList<>());
    }


} 